package com.dymall.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dymall.common.exception.BadRequestException;
import com.dymall.common.utils.UserContext;
import com.dymall.domain.dto.ItemDTO;
import com.dymall.domain.dto.OrderDetailDTO;
import com.dymall.domain.dto.OrderFormDTO;
import com.dymall.domain.po.Order;
import com.dymall.domain.po.OrderDetail;
import com.dymall.mapper.OrderMapper;
import com.dymall.service.CartService;
import com.dymall.service.ItemService;
import com.dymall.service.OrderDetailService;
import com.dymall.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    private final ItemService itemService;
    private final OrderDetailService orderDetailService;
    private final CartService cartService;

    @Override
    public Long createOrder(OrderFormDTO orderFormDTO) {
        // 1.订单数据
        Order order = new Order();
        // 1.1.查询商品
        List<OrderDetailDTO> detailDTOs = orderFormDTO.getDetails();

        // 1.2.获取商品id和数量的Map
        Map<Long, Integer> map = detailDTOs.stream().
                collect(Collectors.toMap(OrderDetailDTO::getItemId, OrderDetailDTO::getNum));
        Set<Long> ids = map.keySet();

        // 1.3.查询商品
        List<ItemDTO> items = itemService.queryItemByIds(ids);
        if(items == null || items.size() < ids.size()){
            throw new BadRequestException("商品不存在");
        }

        // 1.4.基于商品价格、购买数量计算商品总价：totalFee
        int totalFee = 0;
        for(ItemDTO item : items){
            totalFee += item.getPrice() * map.get(item.getId());
        }
        order.setTotalFee(totalFee);
        // 1.5.其它属性
        order.setPaymentType(orderFormDTO.getPaymentType());
        order.setUserId(UserContext.getUser());
        order.setStatus(1);
        // 1.6.将Order写入数据库order表中
        save(order);

        // 2.保存订单详情
        List<OrderDetail> details = buildDetail(order.getId(), items, map);
        orderDetailService.saveBatch(details);
        // 3.清理购物车商品
        cartService.deleteCartItemByIds(ids);

        // 4.扣减库存
        try {
            itemService.deductStock(detailDTOs);
        } catch (Exception e) {
            throw new RuntimeException("库存不足！");
        }
        return order.getId();
    }

    @Override
    public void markOrderPaySuccess(Long id) {
        Order order = new Order();
        order.setId(id).setStatus(2).setPayTime(LocalDateTime.now());
        updateById(order);
    }

    private List<OrderDetail> buildDetail(Long id, List<ItemDTO> items, Map<Long, Integer> map) {
        List<OrderDetail> details = new ArrayList<>(items.size());
        for(ItemDTO item : items){
            OrderDetail detail = new OrderDetail();
            detail.setName(item.getName());
            detail.setSpec(item.getSpec());
            detail.setPrice(item.getPrice());
            detail.setNum(map.get(item.getId()));
            detail.setItemId(item.getId());
            detail.setImage(item.getImage());
            detail.setOrderId(id);
            details.add(detail);
        }
        return details;
    }
}
